package question2;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * Classe gestionnaire generant un fichier HTML 
 * contenant les donnees du capteur.
 * 
 * @author Jacquemin Thibault
 * @author Marleix Mathieu
 *
 */
public class FileHandler  extends Handler<Float>
{
	private final static int MAX= 5;
	private String fileName;
	private int counter;

	private SortedMap<Date, Float> table;

	public FileHandler( String fileName, Handler<Float> successor )
	{
		super( successor );

		this.fileName= fileName;
		this.counter= 0;
		table= new TreeMap<Date, Float>();
	} // FileHandler()

	public boolean handleRequest( Float value )
	{
		Calendar c= Calendar.getInstance();
		table.put(c.getTime(),value);
		counter++;
		if (counter == MAX) {
			try{this.writeHTML();
			}catch(IOException io){
				//io.printStackTrace();
			}finally{
				counter = 0;
			}
		}
		return super.handleRequest( value );
	} // handleRequest()

	/** Cette methode genere un fichier HTML .
	 */
	private void writeHTML() throws IOException
	{
		BufferedWriter bw= new BufferedWriter( new PrintWriter( new FileWriter(
				fileName + ".html" ) ) );
		bw.write( "<html><head><title>mesures du taux d'humidite relative</title>" );
		bw.write( "<meta http-equiv=\"refresh\" content=\"30\">" );
		bw.write( "</head><body><br>\r\n<table border=\"2\" bgcolor=\"#CBFEEA\">" );

		Set<Date> timeLine = table.keySet();
		DateFormat df= DateFormat.getDateInstance( DateFormat.SHORT, Locale.FRANCE );
		DateFormat dt= DateFormat.getTimeInstance( DateFormat.SHORT, Locale.FRANCE );

		for (Date milliS : timeLine) {
			String date= df.format( milliS ) + "-" + dt.format( milliS ) ;
			bw.write("<tr><td>"+date+"</td><td>"+table.get(milliS)+"</td></tr>");
		}

		bw.write( "</table>\r\n</body></html>" );
		bw.close();
	} // writeHTML()

} // FileHandler
